import {page, pageFunc} from "../common/PageBuilder";
import {BasePage, BasePageData} from "../common/core/BasePage";
import {AuthPage} from "../common/partPages/UserPage";
import {userMgr, waitForLogin} from "../../modules/userModule/managers/UserManager";
import {UserInterface} from "../../modules/userModule/UserCommon";
import {pageMgr} from "../../modules/coreModule/managers/PageManager";
import {alertMgr, handleError} from "../../modules/coreModule/managers/AlertManager";
import {field} from "../../modules/coreModule/data/DataLoader";
import {CertAuthPage} from "../certAuth/CertAuthPage";
import {DonationPage} from "../donation/DonationPage";
import {IdenAuthPage} from "../idenAuth/IdenAuthPage";
import {MyApplyPage} from "../myApply/MyApplyPage";
import {MyFollowPage} from "../myFollow/MyFollowPage";
import {MyPubPage} from "../myPub/MyPubPage";
import {PayRecordPage} from "../payRecord/PayRecordPage";
import {PayResultPage} from "../payResult/PayResultPage";
import {PayInterface} from "../../modules/payModule/PayCommon";
import {PrivilegePage} from "../privilege/PrivilegePage";
import {BillListPage} from "../billList/BillListPage";
import {CommissionPage} from "../commission/CommissionPage";
import { storageMgr } from "../../modules/coreModule/managers/StroageManager";
import {UserDetailPage} from "../userDetail/UserDetailPage";
import {appConfigRepo} from "../../modules/coreModule/data/AppConfig";
import {waitForDataLoad} from "../../modules/coreModule/managers/DataManager";
import {ShareAppPage} from "../common/partPages/SharePage";
import {CloudFileUtils, MediaFile} from "../../utils/CloudFileUtils";

const LoginDesc = "个人信息仅用于展示";
const ProtoReadKey = "protoRead";

class Data extends BasePageData {
	@field
	score: number = 0;
	@field
	balance: string = "0.00";
	@field
	publishCnt: number = 0;
	@field
	share: string = "0.00";
	@field
	isShow: boolean = false;
	@field(String)
	officialPhone: string

	// @field(Object)
	// avatar: MediaFile;
}

@page("mine", "我的")
export class MinePage extends BasePage<Data> {

	public data = new Data();

	/**
	 * 部分页
	 */
	public userPage: AuthPage = new AuthPage(
		true, false ,false);
	public shareAppPage = new ShareAppPage();

	onLoad(){
		let isReadProto = storageMgr().getData(ProtoReadKey)
		if (!isReadProto) this.openProto();
	}

	onShow() {
		super.onShow();
		this.loadPhone().then();
		this.loadData().then();
	}

	@waitForLogin
	private async loadData() {
		const res = await UserInterface.GetStat();
		res.balance = res.balance.toFixed(2);
		res.share = res.share.toFixed(2);
		return this.setData({...res});
	}
	@waitForDataLoad
	private async loadPhone() {
		await this.setData({
			officialPhone: appConfigRepo().data.officialPhone
		})
	}

	// region 事件

	@pageFunc
	public tapToLogin() {
		this.userPage.manualLogin(LoginDesc).then();
	}

	@pageFunc
	public async getPhoneNumber(e) {
		console.log(e.detail.code)
		if (!e.detail.code) return;
		// getPhone函数返回值
		await userMgr().getPhone(e.detail.code)
		await this.userPage.setData({
			userInfo: this.userPage.userInfo
		});
	}

	@pageFunc
	@handleError
	public async onAvatarChoose(e: CustomEvent) {
		const tmpFiles = [e.detail.file];
		const files = tmpFiles.map(f => CloudFileUtils.mediaFile2File("user", f));
		const fileIds = await CloudFileUtils.uploadFiles(files, "user");

		console.log("UserInterface", fileIds[0]);

		await UserInterface.EditInfo({avatarUrl: fileIds[0]});
		await this.userPage.setData({"userInfo.avatarUrl": fileIds[0]});
	}

	// region 页面跳转

	@pageFunc
	toDonation() {
		pageMgr().push(DonationPage, {score: this.data.score}).then();
	}

	@pageFunc
	toPayRecord() {
		pageMgr().push(BillListPage).then();
	}

	@pageFunc
	toMyPub(){
		pageMgr().push(MyPubPage).then();
	}

	@pageFunc
	toCommission() {
		pageMgr().push(CommissionPage).then();
	}

	@pageFunc
	toPrivilege() {
		pageMgr().push(PrivilegePage).then();
	}

	@pageFunc
	async toTest() {
		// TODO: 测试
		// const res = await PayInterface.CreateTrade({
		// 	price: 1, description: "测试"
		// });
		// pageMgr().push(PayResultPage, <any>{
		// 	tradeId: res.trade._id
		// }).then();
		pageMgr().push(UserDetailPage, {id: "oZsI_4002m2-ow1YyRbmXjaZCp00"}).then();
	}

	@pageFunc
	toMyApply() {
		pageMgr().push(MyApplyPage).then();
	}

	@pageFunc
	toMyFollow() {
		pageMgr().push(MyFollowPage).then();
	}

	@pageFunc
	notOpened() {
		alertMgr().showAlert("功能暂未开放，敬请期待");
	}

	@pageFunc
	async toIdentAuth() {
		if (!this.userPage.userInfo)
			await alertMgr().showAlert("尚未登录！");
		if (this.userPage.userInfo.identification?.status == 0)
			await pageMgr().push(IdenAuthPage, {identification: this.userPage.userInfo.identification});
		// else if (this.userPage.userInfo.identification?.status == -1) {
		// 	const res = await alertMgr().showAlert(
		// 		"实名认证审核中，点击确定修改认证信息", true);
		// 	if (res.confirm) pageMgr().push(IdenAuthPage).then();
		// }
		else
			pageMgr().push(IdenAuthPage).then();
	}

	@pageFunc
	async toCertAuth() {
		if (!this.userPage.userInfo)
			await alertMgr().showAlert("尚未登录！");
		if (this.userPage.userInfo.certification?.status == 0)
			await pageMgr().push(CertAuthPage, {certification: this.userPage.userInfo.certification});
		// await alertMgr().showAlert("资质认证已完成，无法再次认证");
		// else if(this.userPage.userInfo.certification?.status == -1){
		// 	const res = await alertMgr().showAlert(
		// 		"资质认证审核中，点击确定修改认证信息", true);
		// 	if (res.confirm) pageMgr().push(CertAuthPage).then();
		// }
		else
			pageMgr().push(CertAuthPage).then();
	}

	@pageFunc
	async openProto(){
		this.setData({ isShow: true }).then()
	}
	@pageFunc
	async closeProto(){
		console.log("执行")
		this.setData({ isShow: false }).then()
		storageMgr().setData(ProtoReadKey, true)
	}


	// endregion

	// endregion

}
